#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct Date Date;
typedef struct Family Family;

//Function prototypes
Family *get_person(void);										//Input function
void show_people(bool forwards, Family *pfirst,Family *plast);	//Output function
void release_memory(Family *pfirst);							//Release heap memory


struct Date
{
	int day;
	int month;
	int year;
};

struct Family													//Family structure declaration
{
	Date dob;
	char name[20];
	char father[20];
	char mother[20];
	Family *next;												//Pointer to next structure
	Family *previous;											//Pointer to previous structure
};


int main(int argc, char const *argv[])
{
	Family *first = NULL;										//Pointer to first person
	Family *current = NULL;										//Pointer to current person
	Family *last = NULL;										//Pointer to previouse person
	char more = '\0';											//Test value for ending input


	while(true){
		printf("Do you want to enter details of a%s person (Y or N)?",first!=NULL?"nother":"" );

		scanf(" %c",&more);
		if(tolower(more) == 'n')
			break;

		current = get_person();
		if(first == NULL)
			first = current;									//Set pointer to first Family
		else{
			last->next = current;								//Set next address for previous Family
			current->previous = last;							//Set previous address for current
		}

		last = current;											//Remember for next iteration

	}

	show_people(true,first,last);								//Tell them what we know
	release_memory(first);
	first = last = NULL;

	return 0;
}

Family *get_person(void){
	Family *temp = (Family*)malloc(sizeof(Family));

	printf("\nEnter the name of the person:");
	scanf("%s",temp->name);

	printf("\nEnter %s's date of birth (day month year):", temp->name);
	scanf("%d %d %d",&temp->dob.day,&temp->dob.month,&temp->dob.year);

	printf("\nWho is %s's father? ", temp->name);
	scanf("%s",temp->father);

	printf("\nWho is %s's monther? ",temp->name);
	scanf("%s",temp->mother);

	temp->next = temp->previous = NULL;							//Set pointer members to NULL
	return temp;
}

void show_people(bool forwards, Family *pfirst, Family *plast){
	printf("\n");
	for(Family *pcurrent = forwards?pfirst:plast; pcurrent!=NULL; pcurrent = forwards? pcurrent->next:pcurrent->previous){
		printf("%s was born %d-%d-%d and has %s and %s as parents.\n", 
			pcurrent->name,pcurrent->dob.day,pcurrent->dob.month,pcurrent->dob.year,pcurrent->father,pcurrent->mother);

	}
}

void release_memory(Family *pfirst){
	Family *pcurrent = pfirst;
	Family *temp = NULL;
	while(pcurrent){
		temp = pcurrent;
		pcurrent = pcurrent->next;
		free(temp);
	}
}




